'''
Created on Mar 7, 2012
@author: oabalbin
'''

import os
import sys
import glob
import subprocess
from collections import defaultdict

JOB_ERROR=1
JOB_SUCCESS=0

def nest_dict():
    mydict=defaultdict(list)
    return mydict

def read_calls(tcga_file,inhouse_file):
    '''
    '''
    ifile = open(tcga_file)
    hd=ifile.next()
    g_sps = defaultdict(nest_dict)
    
    for l in ifile:
        f = l.strip('\n').split('\t')
        sample,gene = f[0],f[1]
        g_sps[gene]['tcga'].append(sample)
    ifile.close()
    
    hfile=open(inhouse_file)
    hd2=hfile.next()    
    for l in hfile:
        f = l.strip('\n').split('\t')
        sample,sptype,gene = f[0],f[1],f[2]
        if gene in g_sps:
            if sptype=='CRPC':
                g_sps[gene]['crpc'].append(sample)
            elif  sptype=='PC':
                g_sps[gene]['pc'].append(sample)
    hfile.close()
    return g_sps

def recurrence_tcga_calls(g_sps,tcga_file,tcga_out):
    ifile = open(tcga_file)
    of=open(tcga_out,'w')
    hd=ifile.next().strip('\n').split('\t')
    ol=['sample', 'gene', 'tcga_rec', 'crpc_rec', 'pc_rec']+hd[2:]
    ol= [a.replace(',',';') for a in ol]
    of.write(",".join(ol).replace(',','\t').replace(';',',')+'\n')
    
    for l in ifile:
        f = l.strip('\n').split('\t')
        sample,gene = f[0],f[1]
        tcga_rec=len(g_sps[gene]['tcga'])
        crpc_rec=len(g_sps[gene]['crpc'])
        pc_rec=len(g_sps[gene]['pc'])
        
        ol = [sample,gene, tcga_rec, crpc_rec, pc_rec]+f[2:]
        ol=map(str,ol)
        ol= [a.replace(',',';') for a in ol]
        of.write(",".join(ol).replace(',','\t').replace(';',',')+'\n')
        
    ifile.close()
    of.close()

def calls_in_genes(genelist,inhouse_file,out_file):
    ifile = open(inhouse_file)
    of=open(out_file,'w')
    ol=ifile.next().strip('\n').split('\t')
    ol= [a.replace(',',';') for a in ol]
    of.write(",".join(ol).replace(',','\t').replace(';',',')+'\n')
    print genelist
    for l in ifile:
        f = l.strip('\n').split('\t')
        sample,sptype,gene = f[0],f[1],f[2]
        print gene
        if gene in genelist:
            of.write(l)
        
    ifile.close()
    of.close()

def read_gene_list(file):
    ifile=open(file)
    return [l.strip('\n').split('\t')[0] for l in ifile]
    
        

tcga_file='/data/projects/tcgatest/master_SNV_PRAD.txt'
inhouse_file='/data/projects/tcgatest/TableSNonsyn_04Dec11.txt'
tcga_file_out='/data/projects/tcgatest/master_SNV_PRAD_inhouse_comp.txt'
#g_sps=read_calls(tcga_file,inhouse_file)
#recurrence_tcga_calls(g_sps,tcga_file,tcga_file_out)
gene_file='/data/projects/tcgatest/johnlist_3.txt'#johnlist_hprd.txt'
gene_life_out='/data/projects/tcgatest/johnlist_3.txt_out'#johnlist_hprd_out.txt'
calls_in_genes(read_gene_list(gene_file),inhouse_file,gene_life_out)
